﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Caliburn.Micro;
using JY.Common.Extensions;
using JY.Wpf.Core.Enums;
using JY.Wpf.Core.Events;
using JY.Wpf.Core.Extensions;
using JY.Wpf.Core.Tools;
using JY.Wpf.Core.ViewModelBases;
using JY.Wpf.Test.Views.MVVMDemoViews;
using Newtonsoft.Json;
using SD.IOC.Core.Mediators;

namespace JY.Wpf.Test.ViewModels.MVVMDemoViewModels
{
    /// <summary>
    /// 钉钉机器人消息ViewModel
    /// </summary>
    public class DingTalkMessageViewModel : ViewModelBase
    {
        #region # 变量

        #endregion

        #region # 构造器
        /// <summary>
        /// 构造器
        /// </summary>
        public DingTalkMessageViewModel()
        {
            this.DingTalkApiUrl = "https://oapi.dingtalk.com/robot/send?access_token=b0aecf5d1a726dccd38b5cde98af24f50cf9627a1304650588bef2fc41288071";
        }
        #endregion

        #region # 属性

        #region 消息——string Message
        /// <summary>
        /// 消息
        /// </summary>
        [NotifyPropertyChanged]
        public string Message { get; set; }
        #endregion

        #region 钉钉消息Api地址——string DingTalkApiUrl
        /// <summary>
        /// 钉钉消息Api地址
        /// </summary>
        [NotifyPropertyChanged]
        public string DingTalkApiUrl { get; set; }
        #endregion
        #endregion

        #region # Command方法
        #region # 发送消息——void SendMessage()
        /// <summary>
        /// 发送消息
        /// </summary>
        public async void SendMessage()
        {
            //RestRequest request = new RestRequest(Method.POST);
            //long timestamp = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000);
            //request.AddParameter("timestamp", timestamp);//时间
            //string sign = this.AddSign(timestamp);
            //request.AddParameter("sign", sign);//秘钥


            //request.AddObject(new StringContent(
            //    new { msgtype = "text", text = new { content = $"{this.Message}{DateTime.Now:yyyy-MM-dd HH:mm:ss}" } }
            //        .ToJson(), Encoding.UTF8, "application/json"));

            //RestClient restClient = new RestClient(this.DingTalkApiUrl);
            //IRestResponse response = restClient.Execute(request);

            //if (response.StatusCode == HttpStatusCode.OK)
            //{
            //    this.EventAggregator.PublishOnUIThread(new WarningMessageEvent("钉钉消息发送成功！\r" + response.Content, MessageType.Success));
            //}
            //else
            //{
            //    this.EventAggregator.PublishOnUIThread(new WarningMessageEvent("钉钉消息发送失败！" + response.Content));
            //}
            string result = "";
            //获取毫秒时间戳
            long shijianchuo = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000);
            //获取签名值
            string sign = AddSign(shijianchuo);
            string url = $"{this.DingTalkApiUrl}&timestamp=" + shijianchuo + "&sign=" + sign;

            var obj = new
            {
                msgtype = "text",
                text = new
                {
                    content = this.Message,
                }

            };

            string json = JsonConvert.SerializeObject(obj);
            Console.WriteLine(url);
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/json;charset=utf-8";
            Console.WriteLine(json);

            var bytes = Encoding.UTF8.GetBytes(json);
            req.ContentLength = bytes.Length;
            using (Stream requestStream = req.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            Console.WriteLine(result);

        }
        /// <summary>
        /// 加签
        /// </summary>
        /// <param name="zTime">当前时间戳</param>
        /// <returns></returns>
        private string AddSign(long zTime)
        {
            string secret = "SEC20200c3ad0272258f0dcc2bcc6d3d9944b1d309285e60f2cb9d7a919f6b4043c";
            string stringToSign = zTime + "\n" + secret;
            var encoding = new System.Text.UTF8Encoding();
            byte[] keyByte = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(stringToSign);
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                return HttpUtility.UrlEncode(Convert.ToBase64String(hashmessage), Encoding.UTF8);
            }
        }
        #endregion
        #endregion

        #region # 方法

        #endregion

        #region # 获取页面 —— object GetView(object context = null)
        /// <summary>
        /// 获取页面
        /// </summary>
        /// <param name="context">页面</param>
        /// <returns></returns>
        public override object GetView(object context = null)
        {
            return ResolveMediator.Resolve<DingTalkMessageView>();
        }
        #endregion
    }
}
